package com.gitee.lougnib.hellowebim.common.mybatis.service;

import static com.gitee.lougnib.hellowebim.common.mybatis.mapper.ChatRoomUserEntityDynamicSqlSupport.*;
import static org.mybatis.dynamic.sql.SqlBuilder.*;

import java.util.Date;
import java.util.Optional;

import org.mybatis.dynamic.sql.render.RenderingStrategies;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.gitee.lougnib.hellowebim.common.mybatis.entity.ChatRoomUserEntity;
import com.gitee.lougnib.hellowebim.common.mybatis.mapper.ChatRoomUserMapper;

@Service
public class ChatRoomUserService {

    @Autowired
    private ChatRoomUserMapper chatRoomUserMapper;

    public void saveVisitor(String paramVisitorId, String userAgent) {
        Optional<ChatRoomUserEntity> optionalEntity = selectByVisitorId(paramVisitorId);
        if (optionalEntity.isPresent()) {
            updateAccessTime(optionalEntity.get());
        } else {
            ChatRoomUserEntity entity = new ChatRoomUserEntity();
            entity.setChatRoomId(9999999999L);
            entity.setVisitorId(paramVisitorId);
            entity.setUserAgent(userAgent);
            Integer accessLevel = Integer.valueOf(0);
            entity.setAccessLevel(accessLevel);
            chatRoomUserMapper.insertSelective(entity);
        }
    }

    public Integer getAccessLevel(String paramVisitorId) {
        Optional<ChatRoomUserEntity> entity = selectByVisitorId(paramVisitorId);

        if (entity.isPresent()) {
            return entity.get().getAccessLevel();
        }

        return Integer.valueOf(0);
    }

    private Optional<ChatRoomUserEntity> selectByVisitorId(String paramVisitorId) {
        return chatRoomUserMapper.selectOne(
                select(id, accessLevel, accessCount).from(chatRoomUserEntity).where(visitorId, isEqualTo(paramVisitorId)).build()
                        .render(RenderingStrategies.MYBATIS3));
    }

    private int updateAccessTime(ChatRoomUserEntity entity) {
        if (entity.getAccessCount() == null) {
            entity.setAccessCount(Integer.valueOf(1));
        } else {
            entity.setAccessCount(Integer.valueOf(entity.getAccessCount().intValue() + 1));
        }
        entity.setLastAccessTime(new Date());
        return chatRoomUserMapper.updateByPrimaryKeySelective(entity);
    }
}
